﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RESP_IIWaterAssessment
{

    /*
     * разобраться с комбобоксом работников АВП
     */

    public partial class AVPForm : Form
    {
        RESP_IIWaterAssessment.Entity.tb_avpstate stateAVP;
        RESP_IIWaterAssessment.Entity.RESP_addDataContext resp_data = new RESP_IIWaterAssessment.Entity.RESP_addDataContext(DBClass.RESPContext.Connection);
        //tb_avpstate stateAVP;
        tb_avp avp;
        //tb_member emp;

        int regID;

        bool updateRec = true;
        TextBox newAVPName = new TextBox();

        public AVPForm()
        {
            InitializeComponent();
        }



        private void GetAVPInfo(int avpID)
        {

            stateAVP = resp_data.tb_avpstates.Where(wh => wh.AVPID == avpID && wh.Year == DateTime.Now.Year).SingleOrDefault();
            //stateAVP = DBClass.AVPState.Where(wh => wh.AVPID == avpID && wh.Year == DateTime.Now.Year).SingleOrDefault();
            if (stateAVP == null)
            {

                // изменить цикл на выборку 
                int year = DateTime.Now.Year;
                while (stateAVP == null)
                {
                    year--;
                    //stateAVP = DBClass.AVPState.Where(wh => wh.AVPID == avpID && wh.Year == year).SingleOrDefault();
                    stateAVP = resp_data.tb_avpstates.Where(wh => wh.AVPID == avpID && wh.Year == year).SingleOrDefault();
                    if (year == 1991)
                    {
                        if (InformationClass.Lang)
                            MessageBox.Show("Нет данных");
                        else
                            MessageBox.Show("Маълумотлар йўқ");
                        break;
                    }
                }
                if (stateAVP != null)
                {
                    string msg = InformationClass.Lang?"Перенести состояние АВП в " + DateTime.Now.Year.ToString() + " год":"СИУ ҳолатини " + DateTime.Now.Year.ToString() + " йилга ўтказиш";

                    if (MessageBox.Show(msg, msgClass.msgAchtung, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                            //FHContracts = DBClass.AVPState
                        stateAVP = new RESP_IIWaterAssessment.Entity.tb_avpstate
                        {
                            FHContracts = resp_data.tb_avpstates
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.FHContracts)
                                .SingleOrDefault(),
                            OGMEContracts = resp_data.tb_avpstates
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.OGMEContracts)
                                .SingleOrDefault(),
                            OtherContrats = resp_data.tb_avpstates
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.OtherContrats)
                                .SingleOrDefault(),
                            UISContracts = resp_data.tb_avpstates
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.UISContracts)
                                .SingleOrDefault(),
                            AVPID = avp.ID,
                            FarmerWaterUsers = resp_data.tb_avpstates
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.FarmerWaterUsers)
                                .SingleOrDefault(),
                            HasEquipment = resp_data.tb_avpstates
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.HasEquipment)
                                .SingleOrDefault(),
                            HasFlowJournal = DBClass.AVPState
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.HasFlowJournal)
                                .SingleOrDefault(),
                            HasLimitPlan = resp_data.tb_avpstates
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.HasLimitPlan)
                                .SingleOrDefault(),
                            HasOffice = resp_data.tb_avpstates
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.HasOffice)
                                .SingleOrDefault(),
                            HasUISJournal = DBClass.AVPState
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.HasUISJournal)
                                .SingleOrDefault(),
                            HasWateringPlan = resp_data.tb_avpstates
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.HasWateringPlan)
                                .SingleOrDefault(),
                            HasWaterDemand = resp_data.tb_avpstates
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.HasWateringPlan)
                                .SingleOrDefault(),
                            OtherWaterUsers = resp_data.tb_avpstates
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.OtherWaterUsers)
                                .SingleOrDefault(),
                            StaffQuantity = resp_data.tb_avpstates
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.StaffQuantity)
                                .SingleOrDefault(),
                            WaterGrQuantity = resp_data.tb_avpstates
                                .Where(wh => wh.AVPID == avpID && wh.Year == DBClass.AVPState.Max(mx => mx.Year))
                                .Select(se => se.WaterGrQuantity)
                                .SingleOrDefault(),
                            Year = DateTime.Now.Year,

                        };
                        resp_data.tb_avpstates.InsertOnSubmit(stateAVP);
                        try
                        {
                            resp_data.SubmitChanges();
                            MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                            ShowState();
                        }
                        catch
                        {
                            MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
                        }

                    }
                }
            }
            else
            {
                ShowState();
            }

        }

        private void ShowState()
        {
            chbFlowJournal.Checked = (bool)stateAVP.HasFlowJournal;
            chbHasEquipment.Checked = (bool)stateAVP.HasEquipment;
            chbHasOffice.Checked = (bool)stateAVP.HasOffice;
            chbLimitPlan.Checked = (bool)stateAVP.HasLimitPlan;
            chbUISJournal.Checked = (bool)stateAVP.HasUISJournal;
            chbWateringPlan.Checked = (bool)stateAVP.HasWateringPlan;
            chbDemand.Checked= (bool) stateAVP.HasWaterDemand;
            tbFarmerQuantity.Text = ((int)stateAVP.FarmerWaterUsers).ToString();
            tbGroupQuantity.Text = ((int)stateAVP.WaterGrQuantity).ToString();
            tbOtherQuantity.Text = ((int)stateAVP.OtherWaterUsers).ToString();
            tbStaffQuantity.Text = ((int)stateAVP.StaffQuantity).ToString();


        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
                regID = Convert.ToInt32(cbRegion.SelectedValue);
                cbAVP.Enabled = true;
                //cbAVP.Items.Clear();
                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.DisplayMember = "Name";
                cbAVP.ValueMember = "ID";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;
                cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
            }
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                dtpRegDate.Enabled = tbArea.Enabled = tbStaffQuantity.Enabled = label6.Enabled =
                    groupBox1.Enabled = groupBox2.Enabled = groupBox3.Enabled = groupBox4.Enabled = true;

                string AVPname = cbAVP.Items[cbAVP.SelectedIndex].ToString();
                avp = DBClass.AVP.Where(wh => wh.ID == Convert.ToInt32(cbAVP.SelectedValue)).FirstOrDefault();
                GetAVPInfo(avp.ID);
                dtpRegDate.Value = (DateTime)avp.RegDate;
                tbArea.Text = avp.Area.Value.ToString();

            }
        }

        private object GetManagerName(int StaffID)
        {
            return DBClass.Members.Where(wh => wh.ID == StaffID).Select(se => se.Name).FirstOrDefault();
        }

        private void AVPForm_Load(object sender, EventArgs e)
        {
            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
                cbRegion.DataSource = UtilClass.FillCBRegions();
                cbRegion.DisplayMember = "Name";
                cbRegion.ValueMember = "ID";
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                cbRegion.Enabled = false;
                cbAVP.Enabled = true;
                //cbAVP.Items.Clear();
                regID = InformationClass.regionID;
                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.ValueMember = "ID";
                cbAVP.DisplayMember = "Name";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;

            }

        }

        private void buttonOK_Click(object sender, EventArgs e)
        {

            int FQuantity, OQuantity, SQuantity, GQuantity;
            DateTime RDate;
            decimal area;

            tbArea.Text.GetDecimalOrDefault(out area);
            RDate = dtpRegDate.Value.Date;
            Int32.TryParse(tbFarmerQuantity.Text, out FQuantity);
            Int32.TryParse(tbOtherQuantity.Text, out OQuantity);
            Int32.TryParse(tbStaffQuantity.Text, out SQuantity);
            Int32.TryParse(tbGroupQuantity.Text, out GQuantity);

            if (updateRec && avp != null)
            {
                avp.Area = area;
                avp.Name = cbAVP.Text;
                avp.RegDate = RDate;
                stateAVP.FarmerWaterUsers = FQuantity;
                stateAVP.HasEquipment = chbHasEquipment.Checked;
                stateAVP.HasFlowJournal = chbFlowJournal.Checked;
                stateAVP.HasLimitPlan = chbLimitPlan.Checked;
                stateAVP.HasOffice = chbHasOffice.Checked;
                stateAVP.HasUISJournal = chbUISJournal.Checked;
                stateAVP.HasWateringPlan = chbWateringPlan.Checked;
                stateAVP.HasWaterDemand = chbDemand.Checked;
                stateAVP.OtherWaterUsers = OQuantity;
                stateAVP.StaffQuantity = SQuantity;
                stateAVP.WaterGrQuantity = GQuantity;

            }
            else if (!updateRec && avp == null)
            {
                if (String.IsNullOrEmpty(newAVPName.Text) || DBClass.AVP.Where(wh => wh.Name == newAVPName.Text && wh.RegionID == regID).Select(se => se.Name).ToArray().Contains(newAVPName.Text))
                {
                    MessageBox.Show(msgClass.msgUncorrectData, msgClass.msgAchtung);
                    newAVPName.Focus();
                    newAVPName.SelectionStart = 0;
                    newAVPName.SelectionLength = newAVPName.Text.Length;
                    return;
                }

                avp = new tb_avp
                {
                    Area = area,
                    Name = newAVPName.Text,
                    RegDate = RDate,
                    RegionID = regID
                };

                DBClass.RESPContext.tb_avps.InsertOnSubmit(avp);
                DBClass.RESPContext.SubmitChanges();
                //EmployeesAVPForm emplForm = new EmployeesAVPForm(avp.ID, true, null);
                //emplForm.ShowDialog();

                //mp = emplForm.member;
                //emp.AVPID = avp.ID;

                //DBClass.RESPContext.tb_members.InsertOnSubmit(emp);
                //DBClass.RESPContext.SubmitChanges();
                stateAVP = new RESP_IIWaterAssessment.Entity.tb_avpstate
                {
                    AVPID = avp.ID,
                    FarmerWaterUsers = FQuantity,
                    HasEquipment = chbHasEquipment.Checked,
                    HasFlowJournal = chbFlowJournal.Checked,
                    HasLimitPlan = chbLimitPlan.Checked,
                    HasOffice = chbHasOffice.Checked,
                    HasUISJournal = chbUISJournal.Checked,
                    HasWateringPlan = chbWateringPlan.Checked,
                    HasWaterDemand=chbDemand.Checked,
                    OtherWaterUsers = OQuantity,
                    StaffQuantity = SQuantity,
                    WaterGrQuantity = GQuantity,
                    FHContracts = 0,
                    OGMEContracts = 0,
                    OtherContrats = 0,
                    UISContracts = 0,
                    Year = DateTime.Now.Year,
                };
                resp_data.tb_avpstates.InsertOnSubmit(stateAVP);
            }
            else
            {
                MessageBox.Show(msgClass.msgUncorrectData, msgClass.msgAchtung);
                return;
            }

            try
            {
                if (resp_data.GetChangeSet().Deletes.Count > 0 || resp_data.GetChangeSet().Inserts.Count > 0 || resp_data.GetChangeSet().Updates.Count > 0)
                {
                    resp_data.SubmitChanges();
                    MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                }
            }
            catch
            {
                MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
            }

            updateRec = true;

            this.Close();
        }

        private void butNewAVP_Click(object sender, EventArgs e)
        {
            updateRec = false;
            avp = null;
            splitContainer2.Panel1.Controls.Add(newAVPName);
            newAVPName.Size = cbAVP.Size;
            newAVPName.Location = cbAVP.Location;
            cbAVP.Visible = false;

            dtpRegDate.Enabled = tbArea.Enabled = tbStaffQuantity.Enabled = label6.Enabled =
                    groupBox1.Enabled = groupBox2.Enabled = groupBox3.Enabled = groupBox4.Enabled = true;

            ClearForm();


        }

        private void ClearForm()
        {
            tbArea.Text = tbFarmerQuantity.Text = tbGroupQuantity.Text = tbOtherQuantity.Text =
                tbStaffQuantity.Text = string.Empty;
            dtpRegDate.Value = DateTime.Now.Date;
            chbFlowJournal.Checked = chbHasEquipment.Checked = chbHasOffice.Checked = chbLimitPlan.Checked =
                chbUISJournal.Checked = chbWateringPlan.Checked = false;
        }

        private void butNewManager_Click(object sender, EventArgs e)
        {
            //EmployeesAVPForm emplForm = new EmployeesAVPForm(avp.ID, true, null);

            //if ((emplForm.ShowDialog() == DialogResult.OK))
            //{
            //    emp = emplForm.member;
            //    emp.AVPID = avp.ID;

            //    DBClass.RESPContext.tb_members.InsertOnSubmit(emp);
            //    DBClass.RESPContext.SubmitChanges();                
            //}
        }

        private void deleteAVPButton_Click(object sender, EventArgs e)
        {
            // Проверить удаление - выставить каскадное удаление

            if (avp != null)
            {
                if (MessageBox.Show(msgClass.msgDeleteQuestion, msgClass.msgAchtung, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    DBClass.RESPContext.tb_avps.DeleteOnSubmit(avp);
                    DBClass.RESPContext.SubmitChanges();
                    this.Refresh();

                    ClearForm();
                    cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
                    cbAVP.DataSource = UtilClass.FillAVP(regID);
                    cbAVP.DisplayMember = "Name";
                    cbAVP.ValueMember = "ID";
                    cbAVP.SelectedIndex = -1;
                    cbAVP.Text = string.Empty;
                    cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
                }
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }


}
